/* eslint-disable react/prop-types */

import React, { useEffect, useState } from 'react'
import {Popover, Image, Button, message, Modal} from 'antd'
import PopoverCard from 'pages/popover-card'
import articlesModel from 'pages/model/articles'
import messageModel from 'pages/model/message'
import Link from 'next/link'
import {getAgoAt, storage} from '@/utils/utils'
import { LikeOutlined, MessageOutlined, HeartOutlined, HeartFilled, LikeFilled } from '@ant-design/icons'
import styles from './list-item.module.scss'

function ListItem (props) {

  const {data, searchWord, isMe = false} = props
  const [updateStatus, setUpdateStatus] = useState(false)
  const [isDelete, setIsDelete] = useState(true)
  // 点赞
  const [likeCounts, setLikeCounts] = useState(data.likeCounts)
  const [likeStatus, setLikeStatus] = useState(data.likeStatus)
  const [isclickLike, setIsclickLike] = useState(true)
  // 收藏
  const [collectCounts, setCollectCounts] = useState(data.collectCounts)
  const [collectStatus, setCollectStatus] = useState(data.collectStatus)
  const [isclickCollect, setIsclickCollect] = useState(true)
  const [articleTitle, setArticleTitle] = useState('')
  const updateLikeArticle = () => {
    if (isclickLike) {
      setIsclickLike(false)
      if (JSON.parse(storage.get('next_blog_userInfo'))?.id) {
        articlesModel.updateLikeArticle({
          data: {
            loginId: JSON.parse(storage.get('next_blog_userInfo'))?.id,
            articleId: data.id,
            status: likeStatus
          }
        }).then(data => {
          if (data.success) {
            if (likeStatus === 1) {
              setLikeStatus(0)
              setLikeCounts(likeCounts - 1)
            } else {
              setLikeCounts(likeCounts + 1)
              setLikeStatus(1)
            }
          }
        })
        if (likeStatus === 0 && (JSON.parse(storage.get('next_blog_userInfo'))?.id !== data.userId)) {
          messageModel.addMessage({
            data: {
              loginId: JSON.parse(storage.get('next_blog_userInfo'))?.id,
              articleId: data.id,
              type: 2,
              userId: data.userId
            }
          }).then(data => {
            console.log(data)
          })
        }
      }
      setTimeout(() => {
        setIsclickLike(true) 
      }, 1000)
    } else {
      message.error('操作太频繁了,休息一下吧~')
    }
  }
  const updateCollectArticle = () => {
    if (isclickCollect) {
      setIsclickCollect(false)
      if (JSON.parse(storage.get('next_blog_userInfo'))?.id) {
        articlesModel.updateCollectArticle({
          data: {
            loginId: JSON.parse(storage.get('next_blog_userInfo'))?.id,
            articleId: data.id,
            status: collectStatus
          }
        }).then(data => {
          if (data.success) {
            if (collectStatus === 1) {
              setCollectStatus(0)
              setCollectCounts(collectCounts - 1)
            } else {
              setCollectCounts(collectCounts + 1)
              setCollectStatus(1)
            }
          }
        })
        if (collectStatus === 0 && (JSON.parse(storage.get('next_blog_userInfo'))?.id !== data.userId)) {
          messageModel.addMessage({
            data: {
              loginId: JSON.parse(storage.get('next_blog_userInfo'))?.id,
              articleId: data.id,
              type: 3,
              userId: data.userId
            }
          }).then(data => {
            console.log(data)
          })
        }
      }
      setTimeout(() => {
        setIsclickCollect(true) 
      }, 1000)
    } else {
      message.error('操作太频繁了,休息一下吧~')
    }
  }
  useEffect(() => {
    if (searchWord) {
      const articleTitle = data.title
      console.log(articleTitle)
      const substr = `/${searchWord}/g`
      setArticleTitle(articleTitle.replace(eval(substr), `<span style='color:red;font-weight:bold'>${searchWord}</span>`))
    }
  }, [])
  const confirmDelete = () => {
    Modal.confirm({
      title: '提示',
      content: '是否确认删除?',
      okText: '确认',
      cancelText: '取消',
      onOk () {
        articlesModel.deleteArticle({
          data: {id: data.id}
        }).then(data => {
          if (data.success) setIsDelete(false)
        })
      }
    })
  }
  return (
    <>
      {
        isDelete && <div className={styles.list_container}  id="list_container">
          {
            isMe && <div className={styles.delete}>
              <Button type="text" danger onClick={confirmDelete} >
              删除
              </Button>
            </div>
          }
          
          <div className={styles.list_title}>
            <Popover 
              content={<PopoverCard avatar={data.avatar} type={0} username={data.username} job={data.job} city={data.city} id={data.userId} setFn={setUpdateStatus} status={updateStatus}></PopoverCard>}
            >
              <div className={styles.username}>{data.username}</div>
            </Popover>
            <div className={styles.date}>{getAgoAt(data.createOn)}</div>
            <div className={styles.categories}>
              {
                data.categorieList.length && data.categorieList.map(item => <Link prefetch href={{pathname: '/categories', query: {id: item.id}}} key={item.id}><span  className={styles.categories_item}   >{item.categorieName}</span></Link>)
              }
            </div>
          </div>
          <div className={styles.list_content}>
            <div className={styles.content_text}>
              <div className={styles.title_row}>
                <Link  prefetch href={{pathname: '/articles-detail', query: {id: data.id}}}>
                  {
                    searchWord ? 
                      <div dangerouslySetInnerHTML={{__html: articleTitle}}></div>
                      :
                      <div>{data.title}</div>
                  }
                </Link>
              </div>
              <div className={styles.abstract}>
                <Link prefetch href={{pathname: '/articles-detail', query: {id: data.id}}}>
                  <a>{data.introduction}</a>
                </Link>
                
              </div>
              <div className={styles.content_footer}>
                <div className={styles.fireOutlined} onClick={updateLikeArticle}>{likeStatus === 1 ? <LikeFilled style={{color: '#1e80ff'}}  /> : <LikeOutlined />}  <span className={styles.num} style={{color: likeStatus === 1 ? '#1e80ff' : ''}}>{likeCounts}</span></div>
                <div className={collectStatus ? styles.heartFilled : ''}  onClick={updateCollectArticle}>{collectStatus ? <HeartFilled /> : <HeartOutlined /> }  <span className={styles.num}>{collectCounts}</span></div>
                <div className={styles.messageOutlined}><MessageOutlined /><span className={styles.num}>{data.commentCounts}</span></div>
              </div>
            </div>
            {
              data.coverUrl && <div className={styles.content_img}>
                <Image
                  width={120}
                  height={80}
                  src={data.coverUrl}
                />
              </div>
            }
            
          </div>
        </div>
      }
    </>
    
  )
}

export default ListItem